package com.capgemini.wechat.service;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.capgemini.commons.CSVUtils;
import com.capgemini.wechat.mapper.VehicleMapper;

/**
 * 
 * @author
 * @date
 */
@Service
public class VehicleFileImportService extends FileImportBaseService {
	@Autowired
	private VehicleMapper vehicleMapper;

	@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
	public void importVehicleCSV(String localFilePath) throws IOException {
		List<Map<String, String>> mapList = CSVUtils.readForMap(localFilePath + "/Vehicle.csv", "UTF-8");
		if (null != mapList && !mapList.isEmpty()) {
			List<String> vehicleIds = new LinkedList<String>();
			for (Map<String, String> map : mapList) {
				map.put("ServiceCenterID", "".equals(map.get("ServiceCenterID")) ? null : map.get("ServiceCenterID").matches("[0-9]+") ? map.get("ServiceCenterID") : "0");
				map.put("Year", "".equals(map.get("Year")) ? null : "[0-9]+".matches(map.get("Year")) ? map.get("Year") : "0");
				map.put("CreationDate", "".equals(map.get("CreationDate")) ? null : map.get("CreationDate"));
				map.put("LastModificationDate", "".equals(map.get("LastModificationDate")) ? null : map.get("LastModificationDate"));
				map.put("RegisterDate", "".equals(map.get("RegisterDate")) ? null : map.get("RegisterDate"));
				vehicleIds.add(map.get("VehicleID"));
			}
			int i = 0;
			for(; i < vehicleIds.size() / 1000; i++) {
				vehicleMapper.removeExistingLines(vehicleIds.subList(1000*i, 1000*i + 1000));
			}
			if(vehicleIds.size() % 1000 > 0) {
				vehicleMapper.removeExistingLines(vehicleIds.subList(1000*i, vehicleIds.size()));
			}
			for(i = 0; i < mapList.size() / 1000; i++) {
				vehicleMapper.batchInsert(mapList.subList(1000*i, 1000*i + 1000));
			}
			if(mapList.size() % 1000 > 0) {
				vehicleMapper.batchInsert(mapList.subList(1000*i, mapList.size()));
			}
		}
	}
}
